//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    title: '在线答题系统',
    userInfo: {},
    hasUserInfo: false,
    studentId: 0,
    hasStudentId: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    const stuId = wx.getStorageSync('stuId')
    if (stuId !== 0) {
      this.setData({
        hasStudentId: true
      })
    } else {
      if (stuId) {
        this.setData({
          studentId: stuId,
          hasStudentId: true
        })
      } else {
        app.apis().createStudent().then((res) => {
          wx.setStorageSync('stuId', res.id)
          this.setData({
            studentId: res.id,
            hasStudentId: true
          })
          console.log('@学生编号3', res.id)
        })
      }
    }
    // console.log(student)
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

   
    //获取考题
    app.apis().getExamPaper().then((res) => {
      app.globalData.questions = res.questions //考题
      app.globalData.paper = res.exam_paper
      wx.setStorageSync('totalQuestion', res.questions.length)
      wx.setStorageSync('paperId', res.relation_exam_exam_paper_id)
    })
    
    //统计考题答案,数组方式存储
    wx.setStorageSync('totalAnswer', [])
  },
  getUserInfo: function(e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  goToStudent () {
    console.log('进入练习模式')
    wx.setStorageSync('testMode', 1)
    //重新进入考题清0，答案清空
    wx.setStorageSync('modNum', 0)
    wx.setStorageSync('totalAnswer', [])

    wx.navigateTo({
      url: '/pages/exam/index'
    })
  }, 
  goToStart () {
    console.log('进入考试模式')
    wx.setStorageSync('testMode', 2)
    //重新进入考题清0，答案清空
    wx.setStorageSync('modNum', 0)
    wx.setStorageSync('totalAnswer', [])

    wx.navigateTo({
      url: '/pages/exam/index'
    })
  } 
})
